package com.jt.auth.service;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * UserDetailsService接口的实现类负责:
 * 1.通过查询内存获取用户信息(默认)
 * 2.可以在这里通过dao对象访问数据库
 * 3.可以在这里通过Feign接口调用远端Service
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 此方法在执行登录操作时,由底层自动调用,可以在
     * 此方法中通赤用户名查询用户信息
     * @param username
     * @return 用于认证的用户详情信息对象
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.基于用户我获取远端用户信息
        com.jt.auth.pojo.User user = remoteUserService.selectUserByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("user is not exits");
        }
        //2.基于用户id获取远端用户权限信息
        List<String> permissions = remoteUserService.selectUserPermissions(user.getId());
        //3.封装结果并返回(交给认证对象,完成用户身份认证)

        return new User(username,user.getPassword(), AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));
    }
    //说明:这个方法我们只负责写,不负责调用,这个方法默认就在一个调用链
}
